package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.util.StringUtil;
import com.jzo2o.api.publics.SmsCodeApi;
import com.jzo2o.api.publics.dto.response.BooleanResDTO;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.utils.JwtTool;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.InstitutionRegisterReqDTO;
import com.jzo2o.customer.service.IRegisterService;
import com.jzo2o.customer.service.IServeProviderService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class IRegisterServiceImpl implements IRegisterService {

    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private IServeProviderService serveProviderService;

    @Resource
    private JwtTool jwtTool;

    //机构人员注册
    @Override
    public void register(InstitutionRegisterReqDTO institutionRegisterReqDTO){

        if (StringUtil.isEmpty(institutionRegisterReqDTO.getVerifyCode())){
            throw new BadRequestException("验证码错误，请重新获取");
        }

        ServeProvider serveProviderByPhone = serveProviderService.getServeProviderByPhone(institutionRegisterReqDTO.getPhone());
        if (!ObjectUtil.isNull(serveProviderByPhone)){
            throw new BadRequestException("该手机号已经被注册");
        }

        //远程调用publics服务校验验证码是否正确
       boolean verifyResult = smsCodeApi.verify(institutionRegisterReqDTO.getPhone(),
                SmsBussinessTypeEnum.INSTITION_REGISTER, institutionRegisterReqDTO.getVerifyCode()).getIsSuccess();
        if (!verifyResult){
            throw new BadRequestException("验证码错误，请重新获取");
        }
        //密码哈希加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        String encode = passwordEncoder.encode(institutionRegisterReqDTO.getPassword());

        ServeProvider serveProvider = serveProviderService.add(institutionRegisterReqDTO.getPhone(), UserType.INSTITUTION, encode);

        if (ObjectUtil.isNull(serveProvider)){
            throw new BadRequestException("注册失败");
        }
        //jwtTool.createToken(serveProvider.getId(),serveProvider.getName(),serveProvider.getAvatar(),serveProvider.getType());

    }
}
